package com.know.dao;

import java.util.List;

import org.apache.commons.lang.StringUtils;

import my.db.QueryHelper;

import com.know.entity.Lables;
import com.kzw.bean.Record;
import com.kzw.dao.support.Page;

public class LableDao {

	/**
	 * 查询标签
	 * @return
	 */
	public List<Lables> list() {
		String sql="select *from lables";
		return QueryHelper.query(Lables.class, sql);
	}
	/**
	 * 分页查询
	 */
	public Record findPage(Page<Lables> page) {
		Record record = new Record();
		String sql = "select * from lables";
		if(StringUtils.isNotBlank(page.getOrderBy())) {
			sql += String.format(" order by %s %s", page.getOrderBy(), page.getOrder());
		}
		
		List<Lables> list = QueryHelper.queryPage(Lables.class, sql, page.getPageNo(), page.getPageSize());

	
		//统计总数count
		String sql2 = sql.toLowerCase().replaceFirst("select .*? from", "select count(*) from");
		long count = QueryHelper.stat(sql2);
		
		record.setCount(count);
		record.setData(list);
		
		return record;
	
	}
	/**
	 * 保存标签
	 */
	public void save(Lables lable) {
		String sql= "insert into lables values(null,?,?,?)";//标签表
		QueryHelper.update(sql,lable.getLable_name(),lable.getLable_alias(),lable.getLable_description());
	
	}
	/**
	 * 修改标签
	 */
	public void update(Lables lable) {
		String sql="UPDATE lables SET lable_name=?, lable_alias=?, lable_discription=? WHERE (lable_id=?)";
		QueryHelper.update(sql,lable.getLable_name(),lable.getLable_alias(),lable.getLable_description(),lable.getLable_id());
	}
	/**
	 * 根据ID查找
	 */
	public Lables finById(long parseLong) {
		String sql="select *from lables where lable_id=?";
		Lables lable=QueryHelper.queryUnique(Lables.class, sql, parseLong);
		return lable;
	}
	/**
	 * 删除标签
	 */
	public Record  del(long id) {
		String sql="delete from lables where lable_id =?";
		String sql2="select count(*) num from set_article_lable where lable_id=?";
		String msg="成功删除";
		Record record=new Record(true);
		long num=QueryHelper.stat(sql2, id);//查询关联数量 为0则可以删除
		if(num!=0)
		{
			msg="已有关联文章存在";
			record.setSuccess(false);
		}
		else
		{
			QueryHelper.update(sql, id);
		}
		record.setMsg(msg);
		return record;
	}
	/**
	 * 批量删除
	 * @param ids
	 */
	public Record multiDel(String ids) {
		String sql = "delete from lables where lable_id in (" + ids + ")";
		String sql2="select count(*) num from set_article_lable where in lable_id (" + ids + ")";
		String msg="成功删除";
		Record record=new Record(true);

		long num=QueryHelper.stat(sql2);//查询关联数量 为0则可以删除
		if(num!=0)
		{
			msg="已有关联文章存在";
			record.setSuccess(false);
		}
		else
		{
			
			QueryHelper.update(sql);
		}
		record.setMsg(msg);
		return record;
		
	}

}
